﻿angular.module("umbraco").controller("UE.DealerEditController",
    function ($scope, $routeParams, dealerResource, treeService, notificationsService, navigationService) {
        var vm = this;
        vm.buttonState = "init";
        $scope.dealer = {
            address: "", name: "", responsible: "", contact: "", lat: 0, lng: 0, mistake: false
        };
        $scope.errorMsg = '';
        var id = $routeParams.id.replace("dealer_", "");

        dealerResource.get(id).then(function (response) {
            if (response.Id > 0) {                
                navigationService.syncTree({
                    tree: 'dealerListAlias',
                    path: response.Path,
                    forceReload: true,
                    activate: true
                }).then(function (syncArgs) {
                    $scope.dealer = {
                        address: response.Address, name: response.StoreName, responsible: response.ResponsiblePerson, contact: response.ContactNumber
                        , lat: response.Lat, lng: response.Lng
                    };
                    if (response.IsMistake == 'y') {
                        notificationsService.warning("Warning", "Address resolution error, please update!");
                    }
                });
            } else {
                notificationsService.error("Failed", "Can not get dealer!");
            }
        });

        $scope.updateDealer = function () {
            if ($scope.dealer.address == '') {
                $scope.errorMsg = "输入名字";
            } else {
                vm.buttonState = "busy";
                dealerResource.put(id, $scope.dealer.address, $scope.dealer.name, $scope.dealer.responsible, $scope.dealer.contact).then(function (response) {
                    vm.buttonState = "init";
                    if (response.ErrorCode == 0) {
                        treeService.clearCache({ section: "dealer" });
                        notificationsService.success("Edit Success", "Edit dealer success!");
                        navigationService.syncTree({
                            tree: 'dealerListAlias',
                            path: response.Extend,
                            forceReload: true,
                            activate: true
                        }).then(function (syncArgs) {
                            //console.log(syncArgs);
                        });
                    } else {
                        notificationsService.error("Edit Failed", "Edit failed, " + response.ErrorMsg + "!");
                    }
                });
            }
        }

    }
);